package com.open.component;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.open.service.OpenDictService;
import com.open.util.CryptoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@Component
public class JwtComponent {

    @Autowired
    OpenDictService openDictService;

    private static final String SALT_TOKEN = "chatgpt-template";

    public String generateToken(Map<String, String> mapinfo) {
        Calendar instance = Calendar.getInstance();
        instance.setFirstDayOfWeek(Calendar.SUNDAY);
        instance.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        instance.add(Calendar.WEEK_OF_YEAR, 1);
        JWTCreator.Builder builder = JWT.create();
        mapinfo.forEach(builder::withClaim);
        builder.withExpiresAt(instance.getTime());
        return new CryptoUtil(SALT_TOKEN).encrypt(builder.sign(Algorithm.HMAC256(salt())));
    }

    public String salt(){
        return openDictService.getDict("100004");
    }

    public DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(salt())).build().verify(new CryptoUtil(SALT_TOKEN).decrypt(token));
    }

    public static DecodedJWT getTokenStaticInfo(String token) {
        return JWT.require(Algorithm.HMAC256(JwtComponentHolder.getInstance().salt())).build().verify(new CryptoUtil(SALT_TOKEN).decrypt(token));
    }

    public String getUserWId(HttpServletRequest request){
        String token = request.getHeader("token");
        return getTokenInfo(token).getClaim("wid").asString();
    }

    public String getAdminUserId(HttpServletRequest request){
        String token = request.getHeader("token");
        return getTokenInfo(token).getClaim("uid").asString();
    }

    public String getUserIp(HttpServletRequest request){
        String token = request.getHeader("token");
        return getTokenInfo(token).getClaim("ip").asString();
    }

    public String getUserWId(DecodedJWT jwt){
        return jwt.getClaim("wid").asString();
    }

    public String getAdminUserId(DecodedJWT jwt){
        return jwt.getClaim("uid").asString();
    }
}
